import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
import javax.swing.JOptionPane;



public class SerialFile {
	
	private ArrayList<Record> records;
	private String filename;
	public String fielddelim,valuedelim,recorddelim;
	
	/*Constructor Method*/
	public SerialFile(String fname){
		records = new ArrayList<Record>();
		this.filename = fname;
		this.valuedelim = "=";
		this.fielddelim = "|";
		this.recorddelim = "\n";
		try {
			BufferedReader input = new BufferedReader(new FileReader(filename));
			try{
				String line = null;
				Record temp;
				//Add records to array list one by one
				System.out.println("Entering while loop");
				while((line = input.readLine()) != null){
					System.out.println("Creating new record using parse methods");
					//Create new temporary record
					temp = new Record(Record.parseFirstName(line,valuedelim,fielddelim),Record.parseLastName(line,valuedelim,fielddelim),
							Record.parseID(line,valuedelim,fielddelim),Record.parsePosition(line,valuedelim,fielddelim),Record.parseDel(line,valuedelim));
					System.out.println("Adding record to arraylist");
					//Add the record to arraylist
					records.add(temp);
					System.out.println(records.get(records.size() - 1).toString(valuedelim,fielddelim));
				}
				System.out.println("Records added to array list");
			}
			finally{
				input.close();
			}
		}
		catch(IOException e){
			System.out.println("IO Exception serialfile constructor - maybe file was not found");
		}
		//Saves records in file, each line has its fields in a specific order
		this.saveRecords();
	}
	
	
	/*Save records to file*/
	public void saveRecords(){
		String tofile = "";
		for(int i = 0; i<records.size();i++){
			//Append new record to string of records
			tofile = tofile + records.get(i).toString(valuedelim,fielddelim) + recorddelim;
		}
		try{
			System.out.println("Writing to file...");
			BufferedWriter out = new BufferedWriter(new FileWriter("output.txt"));
			//Write string to file
			out.write(tofile);
			out.close();
			System.out.println("Write complete");
		}
		catch(IOException e){
			System.out.println("IOException saveRecords()");
		}
	}
	

	//add a new record at the end of the file 
	
	public boolean addRecord(int ID, String lastname, String firstname, String position,boolean x){
		int del = 0;
		if(x == true){
			del = 1;
		}
		System.out.println("Adding record: ID" + ID + "  Lastname " + lastname + " Firstname " + firstname + " position " + position + "DEL" + del);
		Record temp = new Record(firstname,lastname,ID,position,del);
		records.add(temp);
		saveRecords();
		return true;
	}
	
	//delete a record by ID, i.e. set deletion marker to 1
	public boolean deleteRecord(int ID){
		int i;
		//Find record
		for(i = 0;records.get(i) != null && records.get(i).getID() != ID;i++){
		}
		//Delete record and save
		if(records.get(i) != null){
			records.get(i).setDelete();
			saveRecords();
			return true;
		}
		else{
			return false;
		}
	}
	
	//delete all record whose field match a specific value
	public boolean deleteRecords(String fieldname,String value){
		int i;
		for(i = 0;i <records.size();i++){
			if(records.get(i).getInfoString(fieldname).equalsIgnoreCase(value)){
					records.get(i).setDelete();
			}
		}
		saveRecords();
		return true;
	}

	//update one field of a specified record
	public boolean updateField(int ID, String fieldname, String value){
		int i;
		for(i = 0; i < records.size() && records.get(i).getID() != ID;i++){
		}
		if(i < records.size()){
			records.get(i).updateRecord(fieldname, value);
			saveRecords();
			System.out.println("Record Updated");
			return true;
		}
		else{
			return false;
		}
	}
	
	//search for records by field value
	public int searchRecord(String fieldname,String value){
		int result = 0;
		int i;
		for(i = 0;i<records.size();i++){
			if(records.get(i).getInfoString(fieldname).equalsIgnoreCase(value)){
				result++;
			}
		}
		return result;
	}
	
	//print record to screen
	public void printRecord(int ID){
		int i;
		//Find record
		for(i = 0;records.get(i) != null && records.get(i).getID() != ID;i++){
		}
		if(records.get(i) != null){
			JOptionPane.showMessageDialog(null,"" + (records.get(i).toString(valuedelim,fielddelim)));
		}
	}
	
	//compress file, ie delete all records marked for deletion
	public void compress(){
		int i;
		for(i = 0;i<records.size();i++){
			if(records.get(i).forDelete() == true){
				records.remove(i);
				i--;
			}
		}
		saveRecords();
	}
	
	//sort file by a field
	public void sort(String fieldname){
		Comparator<Record> thesort = new FieldComparison(fieldname);
		System.out.println("Sorting by " + fieldname);
		Collections.sort(records,thesort);
		saveRecords();
		System.out.println("Sorted + Saved");
	}
	
	//change delimiters
	public void changeDelim(String newValueDelim,String newFieldDelim, String newRecordDelim){
		this.valuedelim = newValueDelim;
		this.fielddelim = newFieldDelim;
		this.recorddelim = newRecordDelim;
	}

}
